"""
仪表盘API路由
"""
from typing import Any, List, Optional, Dict
from fastapi import APIRouter, Depends, HTTPException, status, Query  # pyright: ignore[reportMissingImports]
from motor.motor_asyncio import AsyncIOMotorDatabase  # pyright: ignore[reportMissingImports]
from bson import ObjectId  # pyright: ignore[reportMissingImports]
from datetime import datetime, timedelta

from app.api.deps import get_db, get_current_user
from app.models.user import User
from app.core.permissions import Permissions
from app.core.response import success_response, error_response, ApiResponse
from app.utils.state_utils import get_state_code_by_name_keywords
from app.services.permission_service import PermissionService

router = APIRouter()

@router.get("/overview", response_model=ApiResponse, summary="获取仪表盘概览")
async def get_dashboard_overview(
    project_id: Optional[str] = Query(None, description="项目ID筛选"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    获取仪表盘概览数据
    """
    user_id = ObjectId(current_user.get("user_id"))
    
    # 获取用户可访问的项目ID列表
    accessible_project_ids = await PermissionService.get_user_accessible_project_ids(
        user=current_user,
        db=db
    )
    
    # 项目统计查询条件（用于项目统计，受权限控制）
    project_query = {}
    if accessible_project_ids is None:
        # 管理员，可以访问所有项目
        pass
    elif accessible_project_ids:
        # 普通用户，只能访问指定项目
        project_query["_id"] = {"$in": accessible_project_ids}
    else:
        # 用户没有任何项目权限
        project_query["_id"] = {"$in": []}
    
    # 如果指定了project_id，验证权限并设置查询条件
    project_obj_id = None
    if project_id:
        try:
            project_obj_id = ObjectId(project_id)
            # 验证项目访问权限
            has_access = await PermissionService.check_project_access(
                str(project_obj_id),
                current_user,
                db
            )
            if not has_access:
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="Not enough permissions to access this project"
                )
            project_query["_id"] = project_obj_id
        except HTTPException:
            raise
        except Exception:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid project_id format"
            )
    
    total_projects = await db.projects.count_documents(project_query)
    active_projects = await db.projects.count_documents({**project_query, "status": "active"})
    completed_projects = await db.projects.count_documents({**project_query, "status": "completed"})
    
    # 任务统计 - 统计所有项目的任务（如果指定了project_id则只统计该项目）
    task_query = {}
    if project_obj_id:
        task_query["project_id"] = project_obj_id
    # 如果没有指定project_id，task_query为空，统计所有任务
    
    total_tasks = await db.tasks.count_documents(task_query)
    
    # 获取动态状态代码
    todo_status_code = await get_state_code_by_name_keywords(db, "task", ["待办", "待处理", "todo", "new"])
    in_progress_status_code = await get_state_code_by_name_keywords(db, "task", ["进行中", "in_progress"])
    done_status_code = await get_state_code_by_name_keywords(db, "task", ["已完成", "完成", "done"])
    
    # 统计各状态任务数
    pending_tasks = 0
    in_progress_tasks = 0
    completed_tasks = 0
    
    if todo_status_code:
        pending_tasks = await db.tasks.count_documents({**task_query, "status": todo_status_code})
    if in_progress_status_code:
        in_progress_tasks = await db.tasks.count_documents({**task_query, "status": in_progress_status_code})
    if done_status_code:
        completed_tasks = await db.tasks.count_documents({**task_query, "status": done_status_code}) if done_status_code else 0
    
    # 我的任务统计（基于任务查询条件，但只统计分配给当前用户的任务）
    my_task_query = {**task_query, "assignee_id": user_id}
    my_total_tasks = await db.tasks.count_documents(my_task_query)
    
    my_pending_tasks = 0
    my_in_progress_tasks = 0
    my_completed_tasks = 0
    
    if todo_status_code:
        my_pending_tasks = await db.tasks.count_documents({**my_task_query, "status": todo_status_code})
    if in_progress_status_code:
        my_in_progress_tasks = await db.tasks.count_documents({**my_task_query, "status": in_progress_status_code})
    if done_status_code:
        my_completed_tasks = await db.tasks.count_documents({**my_task_query, "status": done_status_code})
    
    # 缺陷统计 - 统计所有项目的缺陷（如果指定了project_id则只统计该项目）
    defect_query = {}
    if project_obj_id:
        defect_query["project_id"] = project_obj_id
    # 如果没有指定project_id，defect_query为空，统计所有缺陷
    
    total_defects = await db.defects.count_documents(defect_query)
    
    # 动态获取打开状态（包含"新建"、"已分配"、"进行中"、"重新打开"等关键词）
    open_statuses_list = []
    for keywords in [["新建", "新", "new", "open"], ["已分配", "分配", "assigned"], 
                     ["进行中", "进行", "in_progress"], ["重新打开", "重开", "reopened"]]:
        status_code = await get_state_code_by_name_keywords(db, "defect", keywords)
        if status_code:
            open_statuses_list.append(status_code)
    open_defects = await db.defects.count_documents({
        **defect_query,
        "status": {"$in": open_statuses_list} if open_statuses_list else {"$in": []}
    })
    
    # 动态获取已解决状态（包含"已解决"、"解决"、"resolved"等关键词）
    resolved_status_code = await get_state_code_by_name_keywords(db, "defect", ["已解决", "解决", "resolved"])
    resolved_defects = await db.defects.count_documents({
        **defect_query, 
        "status": resolved_status_code
    }) if resolved_status_code else 0
    
    # 动态获取已关闭状态（包含"已关闭"、"关闭"、"closed"等关键词）
    closed_status_code = await get_state_code_by_name_keywords(db, "defect", ["已关闭", "关闭", "closed"])
    closed_defects = await db.defects.count_documents({
        **defect_query, 
        "status": closed_status_code
    }) if closed_status_code else 0
    
    # 需求统计（基于项目数据）- 统计所有项目的需求（如果指定了project_id则只统计该项目）
    requirement_query = {}
    if project_obj_id:
        requirement_query["_id"] = project_obj_id
    # 如果没有指定project_id，requirement_query为空，统计所有项目作为需求
    
    total_requirements = await db.projects.count_documents(requirement_query)
    planning_requirements = await db.projects.count_documents({**requirement_query, "status": "planning"})
    active_requirements = await db.projects.count_documents({**requirement_query, "status": "active"})
    completed_requirements = await db.projects.count_documents({**requirement_query, "status": "completed"})
    on_hold_requirements = await db.projects.count_documents({**requirement_query, "status": "on_hold"})
    cancelled_requirements = await db.projects.count_documents({**requirement_query, "status": "cancelled"})
    
    # 版本统计（基于缺陷环境信息中的版本字段）
    version_stats = {}
    try:
        # 获取所有版本的缺陷分布
        version_pipeline = [
            {"$match": defect_query},
            {"$unwind": {"path": "$environment_info", "preserveNullAndEmptyArrays": True}},
            {"$match": {"environment_info.version": {"$exists": True, "$ne": None, "$ne": ""}}},
            {"$group": {
                "_id": "$environment_info.version",
                "total_defects": {"$sum": 1},
                "open_defects": {
                    # 缺陷打开状态统计已改为动态，通过聚合后的数据在应用层判断
                    "$sum": {"$cond": [{"$ne": ["$status", None]}, 1, 0]}
                },
                "resolved_defects": {
                    # 缺陷已解决状态统计已改为动态，通过聚合后的数据在应用层判断
                    "$sum": 0
                },
                "closed_defects": {
                    # 缺陷已关闭状态统计已改为动态，通过聚合后的数据在应用层判断
                    "$sum": 0
                }
            }},
            {"$sort": {"total_defects": -1}},
            {"$limit": 10}  # 限制返回前10个版本
        ]
        
        version_defect_stats = await db.defects.aggregate(version_pipeline).to_list(length=None)
        
        # 统计版本总数和活跃版本数
        total_versions = len(version_defect_stats)
        active_versions = len([v for v in version_defect_stats if v["open_defects"] > 0])
        
        version_stats = {
            "total_versions": total_versions,
            "active_versions": active_versions,
            "version_defect_distribution": [
                {
                    "version": stat["_id"],
                    "total_defects": stat["total_defects"],
                    "open_defects": stat["open_defects"],
                    "resolved_defects": stat["resolved_defects"],
                    "closed_defects": stat["closed_defects"]
                }
                for stat in version_defect_stats
            ]
        }
    except Exception as e:
        # 如果版本统计出错，返回空统计
        version_stats = {
            "total_versions": 0,
            "active_versions": 0,
            "version_defect_distribution": []
        }
    
    # 用户统计（系统用户总数，所有用户可见）
    total_users = await db.users.count_documents({})
    active_users = await db.users.count_documents({"status": "active"})
    inactive_users = await db.users.count_documents({"status": "inactive"})
    
    user_stats = {
        "total_users": total_users,
        "active_users": active_users,
        "inactive_users": inactive_users
    }
    
    # 项目成员统计（统计所有项目中的成员总数，去重）
    member_query = {}
    if project_obj_id:
        # 如果指定了项目，只统计该项目的成员
        member_query["_id"] = project_obj_id
    elif accessible_project_ids is not None and accessible_project_ids:
        # 如果用户有权限限制，只统计可访问项目的成员
        member_query["_id"] = {"$in": accessible_project_ids}
    # 如果没有指定项目且用户是管理员，member_query为空，统计所有项目的成员
    
    # 使用聚合管道统计去重后的成员数
    member_pipeline = [
        {"$match": member_query},
        {"$unwind": "$members"},
        {"$group": {"_id": "$members.user_id"}},
        {"$count": "total"}
    ]
    
    member_result = await db.projects.aggregate(member_pipeline).to_list(length=1)
    total_project_members = member_result[0]["total"] if member_result and member_result[0].get("total") else 0
    
    member_stats = {
        "total_members": total_project_members
    }
    
    return success_response(data={
        "project_stats": {
            "total_projects": total_projects,
            "active_projects": active_projects,
            "completed_projects": completed_projects
        },
        "task_stats": {
            "total_tasks": total_tasks,
            "pending_tasks": pending_tasks,
            "in_progress_tasks": in_progress_tasks,
            "completed_tasks": completed_tasks
        },
        "my_task_stats": {
            "total_tasks": my_total_tasks,
            "pending_tasks": my_pending_tasks,
            "in_progress_tasks": my_in_progress_tasks,
            "completed_tasks": my_completed_tasks
        },
        "defect_stats": {
            "total_defects": total_defects,
            "open_defects": open_defects,
            "resolved_defects": resolved_defects,
            "closed_defects": closed_defects
        },
        "requirement_stats": {
            "total_requirements": total_requirements,
            "planning_requirements": planning_requirements,
            "active_requirements": active_requirements,
            "completed_requirements": completed_requirements,
            "on_hold_requirements": on_hold_requirements,
            "cancelled_requirements": cancelled_requirements
        },
        "version_stats": version_stats,
        "user_stats": user_stats,
        "member_stats": member_stats
    }, message="获取仪表盘概览成功")

@router.get("/recent-activities", response_model=ApiResponse, summary="获取最近活动")
async def get_recent_activities(
    limit: int = Query(20, ge=1, le=100, description="返回的记录数"),
    project_id: Optional[str] = Query(None, description="项目ID筛选"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    获取最近活动
    """
    user_permissions = current_user.get("permissions", [])
    user_id = ObjectId(current_user.get("user_id"))
    
    # 构建查询条件
    query = {}
    
    # 权限控制
    if Permissions.ADMIN not in user_permissions:
        # 获取用户参与的项目ID列表
        user_projects = await db.projects.find({
            "$or": [
                {"is_public": True},
                {"created_by": user_id},
                {"members.user_id": user_id}
            ]
        }, {"_id": 1}).to_list(length=None)
        
        project_ids = [project["_id"] for project in user_projects]
        query["$or"] = [
            {"project_id": {"$in": project_ids}},
            {"user_id": user_id},
            {"assignee_id": user_id}
        ]
    
    if project_id:
        try:
            query["project_id"] = ObjectId(project_id)
        except Exception:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid project_id format"
            )
    
    activities = []
    
    # 获取最近的任务活动
    recent_tasks = await db.tasks.find(
        query,
        {"title": 1, "status": 1, "assignee_id": 1, "project_id": 1, "updated_at": 1, "created_at": 1}
    ).sort("updated_at", -1).limit(limit // 2).to_list(length=limit // 2)
    
    for task in recent_tasks:
        activities.append({
            "id": str(task["_id"]),
            "type": "task",
            "title": task.get("title", ""),
            "status": task.get("status", ""),
            "project_id": str(task["project_id"]) if task.get("project_id") else None,
            "assignee_id": str(task["assignee_id"]) if task.get("assignee_id") else None,
            "created_at": task.get("created_at", datetime.utcnow()),
            "updated_at": task.get("updated_at", datetime.utcnow())
        })
    
    # 获取最近的缺陷活动
    recent_defects = await db.defects.find(
        query,
        {"title": 1, "status": 1, "assignee_id": 1, "project_id": 1, "updated_at": 1, "created_at": 1}
    ).sort("updated_at", -1).limit(limit // 2).to_list(length=limit // 2)
    
    for defect in recent_defects:
        activities.append({
            "id": str(defect["_id"]),
            "type": "defect",
            "title": defect.get("title", ""),
            "status": defect.get("status", ""),
            "project_id": str(defect["project_id"]) if defect.get("project_id") else None,
            "assignee_id": str(defect["assignee_id"]) if defect.get("assignee_id") else None,
            "created_at": defect.get("created_at", datetime.utcnow()),
            "updated_at": defect.get("updated_at", datetime.utcnow())
        })
    
    # 按更新时间排序
    activities.sort(key=lambda x: x["updated_at"], reverse=True)
    
    return success_response(data=activities[:limit], message="获取最近活动成功")

@router.get("/task-progress", response_model=ApiResponse, summary="获取任务进度趋势")
async def get_task_progress(
    project_id: Optional[str] = Query(None, description="项目ID筛选"),
    days: int = Query(30, ge=1, le=365, description="统计天数"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    获取任务进度趋势
    """
    user_permissions = current_user.get("permissions", [])
    user_id = ObjectId(current_user.get("user_id"))
    
    # 构建查询条件
    query = {}
    
    # 权限控制
    if Permissions.ADMIN not in user_permissions:
        user_projects = await db.projects.find({
            "$or": [
                {"is_public": True},
                {"created_by": user_id},
                {"members.user_id": user_id}
            ]
        }, {"_id": 1}).to_list(length=None)
        
        project_ids = [project["_id"] for project in user_projects]
        query["project_id"] = {"$in": project_ids}
    
    if project_id:
        try:
            query["project_id"] = ObjectId(project_id)
        except Exception:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid project_id format"
            )
    
    # 计算日期范围
    end_date = datetime.utcnow()
    start_date = end_date - timedelta(days=days)
    
    # 按日期分组统计任务创建和完成情况
    pipeline = [
        {
            "$match": {
                **query,
                "created_at": {"$gte": start_date, "$lte": end_date}
            }
        },
        {
            "$group": {
                "_id": {
                    "$dateToString": {
                        "format": "%Y-%m-%d",
                        "date": "$created_at"
                    }
                },
                "created_count": {"$sum": 1},
                "completed_count": {
                    "$sum": {
                        "$cond": [
                            {"$eq": ["$status", "done"]},
                            1,
                            0
                        ]
                    }
                }
            }
        },
        {"$sort": {"_id": 1}}
    ]
    
    task_progress = await db.tasks.aggregate(pipeline).to_list(length=None)
    
    # 填充缺失的日期
    result = []
    current_date = start_date
    progress_dict = {item["_id"]: item for item in task_progress}
    
    while current_date <= end_date:
        date_str = current_date.strftime("%Y-%m-%d")
        if date_str in progress_dict:
            result.append({
                "date": date_str,
                "created_count": progress_dict[date_str]["created_count"],
                "completed_count": progress_dict[date_str]["completed_count"]
            })
        else:
            result.append({
                "date": date_str,
                "created_count": 0,
                "completed_count": 0
            })
        current_date += timedelta(days=1)
    
    return success_response(data=result, message="获取任务进度趋势成功")

@router.get("/workload-distribution", response_model=ApiResponse, summary="获取工作负载分布")
async def get_workload_distribution(
    project_id: Optional[str] = Query(None, description="项目ID筛选"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    获取工作负载分布
    """
    user_permissions = current_user.get("permissions", [])
    user_id = ObjectId(current_user.get("user_id"))
    
    # 构建查询条件
    query = {}
    
    # 权限控制
    if Permissions.ADMIN not in user_permissions:
        user_projects = await db.projects.find({
            "$or": [
                {"is_public": True},
                {"created_by": user_id},
                {"members.user_id": user_id}
            ]
        }, {"_id": 1}).to_list(length=None)
        
        project_ids = [project["_id"] for project in user_projects]
        query["project_id"] = {"$in": project_ids}
    
    if project_id:
        try:
            query["project_id"] = ObjectId(project_id)
        except Exception:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid project_id format"
            )
    
    # 按负责人分组统计任务
    pipeline = [
        {"$match": {**query, "assignee_id": {"$ne": None}}},
        {
            "$group": {
                "_id": "$assignee_id",
                "total_tasks": {"$sum": 1},
                "pending_tasks": {
                    "$sum": {
                        "$cond": [
                            {"$eq": ["$status", "todo"]},
                            1,
                            0
                        ]
                    }
                },
                "in_progress_tasks": {
                    "$sum": {
                        "$cond": [
                            {"$eq": ["$status", "in_progress"]},
                            1,
                            0
                        ]
                    }
                },
                "completed_tasks": {
                    "$sum": {
                        "$cond": [
                            {"$eq": ["$status", "done"]},
                            1,
                            0
                        ]
                    }
                },
                "total_estimated_hours": {"$sum": "$estimated_hours"},
                "total_actual_hours": {"$sum": "$actual_hours"}
            }
        }
    ]
    
    workload_data = await db.tasks.aggregate(pipeline).to_list(length=None)
    
    # 获取用户信息
    user_ids = [item["_id"] for item in workload_data]
    users = await db.users.find(
        {"_id": {"$in": user_ids}},
        {"username": 1, "name": 1, "email": 1}
    ).to_list(length=None)
    
    user_dict = {user["_id"]: user for user in users}
    
    # 组装结果
    result = []
    for item in workload_data:
        user_info = user_dict.get(item["_id"], {})
        result.append({
            "user_id": str(item["_id"]),
            "username": user_info.get("username", "Unknown"),
            "name": user_info.get("name", "Unknown"),
            "email": user_info.get("email", ""),
            "total_tasks": item["total_tasks"],
            "pending_tasks": item["pending_tasks"],
            "in_progress_tasks": item["in_progress_tasks"],
            "completed_tasks": item["completed_tasks"],
            "total_estimated_hours": item["total_estimated_hours"] or 0,
            "total_actual_hours": item["total_actual_hours"] or 0
        })
    
    # 按总任务数排序
    result.sort(key=lambda x: x["total_tasks"], reverse=True)
    
    return success_response(data=result, message="获取工作负载分布成功")

@router.get("/project-health", response_model=ApiResponse, summary="获取项目健康度")
async def get_project_health(
    project_id: Optional[str] = Query(None, description="项目ID筛选"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    获取项目健康度指标
    """
    user_permissions = current_user.get("permissions", [])
    user_id = ObjectId(current_user.get("user_id"))
    
    # 构建项目查询条件
    project_query = {}
    if Permissions.PROJECT_READ_ALL not in user_permissions and Permissions.ADMIN not in user_permissions:
        project_query = {
            "$or": [
                {"is_public": True},
                {"created_by": user_id},
                {"members.user_id": user_id}
            ]
        }
    
    if project_id:
        try:
            project_query["_id"] = ObjectId(project_id)
        except Exception:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid project_id format"
            )
    
    # 获取项目列表
    projects = await db.projects.find(
        project_query,
        {"name": 1, "status": 1, "start_date": 1, "end_date": 1, "created_at": 1}
    ).to_list(length=None)
    
    result = []
    
    # 获取动态状态代码（在循环外获取，避免重复查询）
    done_status_code = await get_state_code_by_name_keywords(db, "task", ["已完成", "完成", "done"])
    
    for project in projects:
        project_obj_id = project["_id"]
        
        # 任务统计 - 使用动态状态
        
        total_tasks = await db.tasks.count_documents({"project_id": project_obj_id})
        completed_tasks = await db.tasks.count_documents({
            "project_id": project_obj_id,
            "status": done_status_code
        }) if done_status_code else 0
        overdue_tasks = await db.tasks.count_documents({
            "project_id": project_obj_id,
            "due_date": {"$lt": datetime.utcnow()},
            "status": {"$ne": done_status_code} if done_status_code else {}
        })
        
        # 缺陷统计 - 从状态管理系统动态获取状态
        total_defects = await db.defects.count_documents({"project_id": project_obj_id})
        # 动态获取打开状态（包含"新建"、"已分配"、"进行中"、"重新打开"等关键词）
        open_statuses_list = []
        for keywords in [["新建", "新", "new", "open"], ["已分配", "分配", "assigned"], 
                         ["进行中", "进行", "in_progress"], ["重新打开", "重开", "reopened"]]:
            status_code = await get_state_code_by_name_keywords(db, "defect", keywords)
            if status_code:
                open_statuses_list.append(status_code)
        open_defects = await db.defects.count_documents({
            "project_id": project_obj_id,
            "status": {"$in": open_statuses_list} if open_statuses_list else {"$in": []}
        })
        
        # 计算健康度指标
        task_completion_rate = (completed_tasks / total_tasks * 100) if total_tasks > 0 else 100
        overdue_rate = (overdue_tasks / total_tasks * 100) if total_tasks > 0 else 0
        defect_rate = (open_defects / (total_tasks + total_defects) * 100) if (total_tasks + total_defects) > 0 else 0
        
        # 计算项目进度
        project_progress = 0
        if project.get("start_date") and project.get("end_date"):
            total_duration = (project["end_date"] - project["start_date"]).days
            elapsed_duration = (datetime.utcnow() - project["start_date"]).days
            if total_duration > 0:
                project_progress = min(elapsed_duration / total_duration * 100, 100)
        
        # 计算综合健康度评分
        health_score = (
            task_completion_rate * 0.4 +
            (100 - overdue_rate) * 0.3 +
            (100 - defect_rate) * 0.2 +
            min(project_progress, task_completion_rate) * 0.1
        )
        
        # 确定健康度等级
        if health_score >= 80:
            health_level = "excellent"
        elif health_score >= 60:
            health_level = "good"
        elif health_score >= 40:
            health_level = "warning"
        else:
            health_level = "critical"
        
        result.append({
            "project_id": str(project_obj_id),
            "project_name": project["name"],
            "project_status": project["status"],
            "total_tasks": total_tasks,
            "completed_tasks": completed_tasks,
            "overdue_tasks": overdue_tasks,
            "total_defects": total_defects,
            "open_defects": open_defects,
            "task_completion_rate": round(task_completion_rate, 2),
            "overdue_rate": round(overdue_rate, 2),
            "defect_rate": round(defect_rate, 2),
            "project_progress": round(project_progress, 2),
            "health_score": round(health_score, 2),
            "health_level": health_level
        })
    
    # 按健康度评分排序
    result.sort(key=lambda x: x["health_score"], reverse=True)
    
    return success_response(data=result, message="获取项目健康度成功")

@router.get("/my-dashboard", response_model=ApiResponse, summary="获取个人仪表盘")
async def get_my_dashboard(
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
) -> Any:
    """
    获取个人仪表盘数据
    """
    user_id = ObjectId(current_user.get("user_id"))
    
    # 获取动态状态代码
    todo_status_code = await get_state_code_by_name_keywords(db, "task", ["待办", "待处理", "todo", "new"])
    in_progress_status_code = await get_state_code_by_name_keywords(db, "task", ["进行中", "in_progress"])
    done_status_code = await get_state_code_by_name_keywords(db, "task", ["已完成", "完成", "done"])
    
    # 我的任务统计
    my_tasks = {
        "total": await db.tasks.count_documents({"assignee_id": user_id}),
        "todo": await db.tasks.count_documents({"assignee_id": user_id, "status": todo_status_code}) if todo_status_code else 0,
        "in_progress": await db.tasks.count_documents({"assignee_id": user_id, "status": in_progress_status_code}) if in_progress_status_code else 0,
        "done": await db.tasks.count_documents({"assignee_id": user_id, "status": done_status_code}) if done_status_code else 0,
        "overdue": await db.tasks.count_documents({
            "assignee_id": user_id,
            "due_date": {"$lt": datetime.utcnow()},
            "status": {"$ne": done_status_code} if done_status_code else {}
        })
    }
    
    # 我的缺陷统计 - 从状态管理系统动态获取状态
    # 动态获取打开状态（包含"新建"、"已分配"、"进行中"、"重新打开"等关键词）
    open_statuses_list = []
    for keywords in [["新建", "新", "new", "open"], ["已分配", "分配", "assigned"], 
                     ["进行中", "进行", "in_progress"], ["重新打开", "重开", "reopened"]]:
        status_code = await get_state_code_by_name_keywords(db, "defect", keywords)
        if status_code:
            open_statuses_list.append(status_code)
    my_defects = {
        "assigned": await db.defects.count_documents({"assignee_id": user_id}),
        "reported": await db.defects.count_documents({"reporter_id": user_id}),
        "open": await db.defects.count_documents({
            "assignee_id": user_id,
            "status": {"$in": open_statuses_list} if open_statuses_list else {"$in": []}
        })
    }
    
    # 我的需求统计（基于项目数据模拟）
    # 获取我参与的项目作为需求
    my_requirement_projects = await db.projects.find({
        "$or": [
            {"created_by": user_id},
            {"members.user_id": user_id}
        ]
    }).to_list(length=None)
    
    my_requirements = {
        "total": len(my_requirement_projects),
        "pending": len([p for p in my_requirement_projects if p.get("status") == "planning"]),
        "in_progress": len([p for p in my_requirement_projects if p.get("status") == "active"]),
        "completed": len([p for p in my_requirement_projects if p.get("status") == "completed"]),
        "cancelled": len([p for p in my_requirement_projects if p.get("status") == "cancelled"])
    }
    
    # 我参与的项目
    my_projects = await db.projects.find({
        "$or": [
            {"created_by": user_id},
            {"members.user_id": user_id}
        ]
    }, {"name": 1, "status": 1}).to_list(length=None)
    
    # 最近的任务
    recent_tasks = await db.tasks.find(
        {"assignee_id": user_id},
        {"title": 1, "status": 1, "priority": 1, "due_date": 1, "project_id": 1}
    ).sort("updated_at", -1).limit(10).to_list(length=10)
    
    # 即将到期的任务
    upcoming_tasks = await db.tasks.find({
        "assignee_id": user_id,
        "status": {"$ne": done_status_code} if done_status_code else {},
        "due_date": {
            "$gte": datetime.utcnow(),
            "$lte": datetime.utcnow() + timedelta(days=7)
        }
    }, {"title": 1, "due_date": 1, "priority": 1, "project_id": 1}).sort("due_date", 1).to_list(length=10)
    
    return success_response(data={
        "my_tasks": my_tasks,
        "my_defects": my_defects,
        "my_requirements": my_requirements,
        "my_projects": [
            {
                "id": str(project["_id"]),
                "name": project["name"],
                "status": project["status"]
            }
            for project in my_projects
        ],
        "recent_tasks": [
            {
                "id": str(task["_id"]),
                "title": task["title"],
                "status": task["status"],
                "priority": task["priority"],
                "due_date": task.get("due_date"),
                "project_id": str(task["project_id"]) if task.get("project_id") else None
            }
            for task in recent_tasks
        ],
        "upcoming_tasks": [
            {
                "id": str(task["_id"]),
                "title": task["title"],
                "due_date": task.get("due_date"),
                "priority": task["priority"],
                "project_id": str(task["project_id"]) if task.get("project_id") else None
            }
            for task in upcoming_tasks
        ]
    }, message="获取个人仪表盘成功")